package com.stu.design_patterns.singleton;

public class Singleton03DoubleCheck {
  private static volatile Singleton03DoubleCheck singleton;
  private Singleton03DoubleCheck() {}

  // public static synchronized Singleton03DoubleLock getInstance() {
  //   if(singleton == null) singleton = new Singleton03DoubleLock();
  //   return singleton;
  // }
  // public static synchronized Singleton03DoubleLock getInstance() {
  //   synchronized(Singleton03DoubleLock.class) {
  //     if(singleton == null) singleton = new Singleton03DoubleLock();
  //   }
  //   return singleton;
  // }
  // 上面两端代码等价

  // 本方法是对第二段代码的优化，如果已经存在实例，那么线程可以直接获取实例，而不需要获取锁
  public static Singleton03DoubleCheck getInstance() {
    if(singleton == null) {
      synchronized(Singleton03DoubleCheck.class) {
        if(singleton == null) singleton = new Singleton03DoubleCheck();
      }
    }
    return singleton;
  }
  public void say() { System.out.println("双重检查锁式"); }
}
